import wx_login from '../api/interface/login';
import service from './service';

interface IUserInfo {
	nickName: string;
	gender: number;
	language: string;
	city: string;
	province: string;
	country: string;
	avatarUrl: string;
}
interface Ires {
	code: number;
	msg: string;
	userInfo: {
		_id: string;
		usercode: string;
		user_name: string;
		name_spell: string;
		is_disabled: boolean;
		create_time: number;
		productid: string;
		avatar_path: string;
		avatar_name: string;
		avatar_type: string;
		email: string;
		phone: string;
		last_login_time: string;
		phone_verified: boolean;
		email_verified: boolean;
		is_admin: string;
		sessionid: string;
	};
}

export default async function active_login(spaceid: string, policyno: string, wx_user_info: IUserInfo) {
	const { nickName, avatarUrl } = wx_user_info;

	const info = await get_user_code(spaceid, policyno, nickName, avatarUrl);
	wx.setStorageSync('sessionid', 'sessionid=' + info.userInfo.sessionid + '; Path=/');
	return info;
}

/**
 * 根据wxapp-code,openid等信息，向pub_user表内新增用户，并登录，返回用户信息
 */
async function get_user_code(spaceid: string, policyno: string, nickName: any, avatarUrl: string) {
	const res_code = await wx_login();
	const params = {
		avatarUrl,
		code: res_code.code,
		logintype: 'weixin_applet',
		nickName,
		policyno,
		spaceid
	};
	return await service<Ires>('thirdpart.weixinapplet.login', params);
}
